﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Sol_NetCoreDemo.Controllers.JWT
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class JWTCheckController : ControllerBase
    {

        [HttpGet("CheckJWT")]
        public ActionResult CheckJWT()
        {
            string passWord = Request.Query["passWord"];
            return Ok(new { Account = CheckAuthorized() });
        }

        [HttpGet]//此处不是用掉调用API接口的，因为这里不加，只写方法 Swagger 会报错
        /// <summary>
        ///  验证JWT
        /// </summary>
        /// <returns></returns>
        public string CheckAuthorized()
        {
            //如果使用 Session， Startup 需添加    services.AddSession();
            //HttpContext.Session.SetString("name","123");
            //String name = HttpContext.Session.GetString("name");
            //if (name == null)
            //{
            //    //重定向到登录页面
            //    HttpContext.Response.Redirect("Home/Login");
            //    return;
            //}

            string account = string.Empty;
            try
            {
                account = HttpContext.User.Claims.First(c => c.Type == "Account").Value;
            }
            catch (Exception ex)
            {
                account = ex.ToString();
                account = "验证失败";
            }
            return account;
        }

    }
}